package com.ruicar.afs.cloud.afscase.channel.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.afscase.channel.common.Constants;
import com.ruicar.afs.cloud.afscase.channel.condition.*;
import com.ruicar.afs.cloud.afscase.channel.entity.*;
import com.ruicar.afs.cloud.afscase.channel.service.*;
import com.ruicar.afs.cloud.afscase.channel.utils.BlackDic;
import com.ruicar.afs.cloud.afscase.channel.vo.AllCarDealerVo;
import com.ruicar.afs.cloud.afscase.channel.vo.ChannelDealer;
import com.ruicar.afs.cloud.afscase.channel.vo.ChannelQuotalnfoToCaseVo;
import com.ruicar.afs.cloud.common.core.log.annotation.SysLog;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.ChannelBelongEnum;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

import static com.ruicar.afs.cloud.afscase.channel.common.Constants.DIRECTCARDEALER;

/**
 * @author: sang jian
 * @date: 2020/5/14 11:01
 * @description:
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/carDealer")
public class CarDealerController {

    /**
     * 收款账号
     */
    @Autowired
    private ChannelAccountInfoService channelAccountInfoService;

    /**
     * 合作商车商关联
     */
    @Autowired
    private ChannelCoopeCardealerService channelCoopeCardealerService;

    /**
     * 风控数据
     */
    @Autowired
    private ChannelRiskInfoService channelRiskInfoService;

    /**
     * 保证金
     */
    @Autowired
    private ChannelQuotaInfoService channelQuotaInfoService;

    @Autowired
    private DirectCarDealerService directCarDealerService;


    @Autowired
    private CarDealerService carDealerService;
    @Autowired
    private ChannelBaseInfoService channelBaseInfoService;

    @Autowired
    private ChannelMainBrandService channelMainBrandService;

    /**
     * 授权区域
     */
    @Autowired
    private ChannelAuthorizeRegionService channelAuthorizeRegionService;

    /**
     * 授权车型
     */
    @Autowired
    private ChannelAuthorizeVehicleService channelAuthorizeVehicleTempService;


    @PostMapping("/addCarDealer")
    @ApiOperation(value = "增加普通车商")
    @Transactional(rollbackFor = Exception.class)
    public IResponse addCarDealerToCase(@RequestBody CarDealerCondition condition) {

        CommonCarDealer commonCarDealer = condition.getCommonCarDealer();
        ChannelCoopeCardealer temp = condition.getChannelCoopeCardealerTemp();
        List<ChannelCoopeCardealer> channelCoopeCardealerTemps = condition.getChannelCoopeCardealerTemps();
        String[] mainBrand = condition.getMainBrand();

        boolean result2 = carDealerService.saveOrUpdate(commonCarDealer);
        channelCoopeCardealerService.remove(Wrappers.<ChannelCoopeCardealer>query().lambda()
                .eq(ChannelCoopeCardealer::getCardealerId, commonCarDealer.getId())
                .eq(ChannelCoopeCardealer::getCardealerType, Constants.COMMONCARDEALER)
        );

        boolean result3 = channelCoopeCardealerService.saveBatch(channelCoopeCardealerTemps);

        //更新车商主营品牌
        List<ChannelMainBrand> mainBrandList = channelMainBrandService.list(Wrappers.<ChannelMainBrand>query().lambda()
                .eq(ChannelMainBrand::getChannelId, commonCarDealer.getId())
                .eq(ChannelMainBrand::getChannelBelong, Constants.COMMONCARDEALER)
        );
        if (mainBrandList != null && mainBrandList.size() > 0) {
            for (ChannelMainBrand brand : mainBrandList) {
                channelMainBrandService.removeById(brand.getId());
            }
        }
        List<ChannelMainBrand> channelMainBrandList = new ArrayList<>();
        if (mainBrand != null && mainBrand.length > 0) {
            for (String main : mainBrand) {
                ChannelMainBrand channelMainBrand = new ChannelMainBrand();
                String code = main.split(",")[0];
                String title = main.split(",")[1];
                channelMainBrand.setChannelId(commonCarDealer.getId());
                channelMainBrand.setCode(code);
                channelMainBrand.setTitle(title);
                channelMainBrand.setChannelBelong(Constants.COMMONCARDEALER);
                channelMainBrandList.add(channelMainBrand);
            }
            channelMainBrandService.saveOrUpdateBatch(channelMainBrandList);
        }
        return result2 && result3 ? IResponse.success("保存成功") : IResponse.fail("保存失败");
    }

    @GetMapping("/CarDealListForZY")
    @ApiOperation(value = "根据合作商账户返回此账户下的车商列表信息")
    public IResponse getCarDealersByUserId(CarDealerCondition condition) {
        String userId = condition.getUserId();
        String cardealerType = condition.getCardealerType();
        String channelId = condition.getChannelId();
        String businessType = condition.getBusinessType();
        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(cardealerType) || StringUtils.isEmpty(channelId)) {
            return IResponse.fail("查询参数为空");
        }
        if (DIRECTCARDEALER.equals(cardealerType) && businessType == null) {
            return IResponse.fail("直营合作商必传业务类型");
        }
        String aSwitch = null;
        List<ChannelBaseInfo> channelList = channelBaseInfoService.list(Wrappers.<ChannelBaseInfo>query().lambda()
                .eq(ChannelBaseInfo::getChannelId, channelId));
        if (channelList != null && channelList.size() > 0) {
            aSwitch = channelList.get(0).getPersonRelCardealerSwitch();
        } else {
            return IResponse.fail("渠道基本信息表中无此合作商信息");
        }
        return carDealerService.getCarDealersByUserId(userId, cardealerType, aSwitch, channelId, businessType);
    }

    @RequestMapping(value = "/saveCommonCarDealer", method = RequestMethod.POST)
    @ApiOperation(value = "保存普通车商申请信息")
    @SysLog("保存普通车商申请信息")
    @Transactional(rollbackFor = Exception.class)
    public IResponse saveCommonCarDealer(@RequestBody CarDealerCondition condition) {

        boolean result;
        boolean carDealerResult;
        boolean coopeResult;
        boolean mainBrandresult = true;

        //基本信息
        CommonCarDealer commonCarDealer = condition.getCommonCarDealer();
        carDealerResult = carDealerService.saveOrUpdate(commonCarDealer);
        //关联表信息
        ChannelCoopeCardealer channelCoopeCardealerTemp = condition.getChannelCoopeCardealerTemp();
        channelCoopeCardealerService.remove(Wrappers.<ChannelCoopeCardealer>query().lambda()
                .eq(ChannelCoopeCardealer::getCardealerType, Constants.COMMONCARDEALER)
                .eq(ChannelCoopeCardealer::getChannelId, channelCoopeCardealerTemp.getChannelId())
                .eq(ChannelCoopeCardealer::getCardealerId, commonCarDealer.getId())
        );
        coopeResult = channelCoopeCardealerService.saveOrUpdate(channelCoopeCardealerTemp);

        //主营品牌
        List<ChannelMainBrand> channelMainBrandList = condition.getChannelMainBrandList();
        channelMainBrandService.remove(Wrappers.<ChannelMainBrand>query().lambda()
                .eq(ChannelMainBrand::getChannelId, commonCarDealer.getId())
                .eq(ChannelMainBrand::getChannelBelong, Constants.COMMONCARDEALER));

        if (channelMainBrandList.size() > 0) {
            for (ChannelMainBrand channelMainBrand : channelMainBrandList) {
                channelMainBrand.setId(null);
            }
            int size = channelMainBrandList.size();
            if (size <= 1000) {
                mainBrandresult = channelMainBrandService.saveBatch(channelMainBrandList);
            } else {
                for (int i = 0; i < size / 1000; i++) {
                    if (size / 1000 - i > 1) {
                        mainBrandresult = channelMainBrandService.saveBatch(channelMainBrandList.subList(1000 * i, 1000 * i + 999));
                    } else {
                        mainBrandresult = channelMainBrandService.saveBatch(channelMainBrandList.subList(1000 * i, size - 1));
                    }
                }
            }
        }
        result = carDealerResult && coopeResult && mainBrandresult;
        return IResponse.success(result);
    }


    @RequestMapping(value = "/saveDirectCarDealer", method = RequestMethod.POST)
    @ApiOperation(value = "保存直营车商申请信息")
    @SysLog("保存直营车商申请信息")
    @Transactional(rollbackFor = Exception.class)
    public IResponse saveDirectCarDealer(@RequestBody DirectCarDealerCondition condition) {

        boolean result;
        boolean carDealerResult;
        boolean coopeResult = true;
        boolean mainBrandresult = true;
        boolean riskResult = true;
        boolean quotaResult = true;
        boolean regionResult = true;
        boolean accountResult = true;
        boolean vehicleResult = true;
        
        //通过id查基本信息
        DirectCarDealer dealer = condition.getChannelBaseInfoTemp();
        carDealerResult = directCarDealerService.saveOrUpdate(dealer);

        //查中间表信息
        ChannelCoopeCardealer coopeCardealerTemp = condition.getChannelCoopeCardealerTemp();

        List<ChannelCoopeCardealer> channelCoopeCardealers = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealer>query().lambda()
                .eq(ChannelCoopeCardealer::getCardealerType, DIRECTCARDEALER)
                .eq(ChannelCoopeCardealer::getChannelId, coopeCardealerTemp.getChannelId())
                .eq(ChannelCoopeCardealer::getCardealerId, dealer.getId())
        );
        if(CollectionUtil.isEmpty(channelCoopeCardealers)){
            coopeResult = channelCoopeCardealerService.saveOrUpdate(coopeCardealerTemp);
        }

        if("channelAdmin".equals(coopeCardealerTemp.getCreateBy())){
            List<ChannelCoopeCardealer> tempList = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealer>query().lambda()
                    .eq(ChannelCoopeCardealer::getCardealerId, dealer.getId())
                    .eq(ChannelCoopeCardealer::getCardealerType, DIRECTCARDEALER)
            );
            if(CollectionUtil.isNotEmpty(tempList)){
                for (ChannelCoopeCardealer temp1 : tempList){
                    temp1.setStatus(coopeCardealerTemp.getStatus());
                    channelCoopeCardealerService.updateById(temp1);
                }
            }
        }else{
            List<ChannelCoopeCardealer> coopeCardealerTempList = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealer>query().lambda()
                    .eq(ChannelCoopeCardealer::getCardealerId, dealer.getId())
                    .eq(ChannelCoopeCardealer::getCardealerType, DIRECTCARDEALER)
                    .eq(ChannelCoopeCardealer::getChannelId, coopeCardealerTemp.getChannelId())
            );
            if(CollectionUtil.isNotEmpty(coopeCardealerTempList)){
                for (ChannelCoopeCardealer temp1 : coopeCardealerTempList){
                    temp1.setStatus(coopeCardealerTemp.getStatus());
                    channelCoopeCardealerService.updateById(temp1);
                }
            }
        }
        //查品牌信息
        List<ChannelMainBrand> mainBrandList = condition.getMainBrandList();
        channelMainBrandService.remove(Wrappers.<ChannelMainBrand>query().lambda()
                .eq(ChannelMainBrand::getChannelId, dealer.getId())
                .eq(ChannelMainBrand::getChannelBelong, DIRECTCARDEALER));
        if (mainBrandList != null && mainBrandList.size() > 0) {
            for (ChannelMainBrand channelMainBrand : mainBrandList) {
                channelMainBrand.setId(null);
                // channelMainBrandService.save(channelMainBrand);
            }

            int size = mainBrandList.size();
            if (size <= 1000) {
                mainBrandresult= channelMainBrandService.saveBatch(mainBrandList);
            } else {
                for (int i = 0; i < size / 1000; i++) {
                    if (size / 1000 - i > 1) {
                        mainBrandresult = channelMainBrandService.saveBatch(mainBrandList.subList(1000 * i, 1000 * i + 999));
                    } else {
                        mainBrandresult = channelMainBrandService.saveBatch(mainBrandList.subList(1000 * i, size - 1));
                    }
                }
            }

        }

        //查风控信息
        List<ChannelRiskInfo> riskInfoTempList = condition.getChannelRiskInfoList();
        channelRiskInfoService.remove(Wrappers.<ChannelRiskInfo>query().lambda()
                .eq(ChannelRiskInfo::getChannelId, dealer.getId()));
        if (riskInfoTempList.size() > 0 && riskInfoTempList != null) {
            for (ChannelRiskInfo channelRiskInfo : riskInfoTempList) {
                channelRiskInfo.setId(null);
                riskResult = channelRiskInfoService.save(channelRiskInfo);
            }
        }

        //查额度表
        List<ChannelQuotaInfo> quotaInfoTempList = condition.getChannelQuotaInfoTempList();
        channelQuotaInfoService.remove(Wrappers.<ChannelQuotaInfo>query().lambda()
                .eq(ChannelQuotaInfo::getChannelId, dealer.getId()));
        if (quotaInfoTempList.size() > 0 && quotaInfoTempList != null) {
            for (ChannelQuotaInfo list : quotaInfoTempList) {
                list.setId(null);
                quotaResult = channelQuotaInfoService.save(list);
            }
        }

        //授权车型
        List<ChannelAuthorizeVehicle> authorizeVehicleTempList = condition.getChannelAuthorizeVehicleList();
        channelAuthorizeVehicleTempService.remove(Wrappers.<ChannelAuthorizeVehicle>query().lambda()
                .eq(ChannelAuthorizeVehicle::getChannelId, dealer.getId()));
        if (authorizeVehicleTempList.size() > 0 && authorizeVehicleTempList != null) {
            for (ChannelAuthorizeVehicle list : authorizeVehicleTempList) {
                list.setId(null);
                //     channelAuthorizeVehicleTempService.save(list);
            }

            int size = authorizeVehicleTempList.size();
            if (size <= 1000) {
                vehicleResult = channelAuthorizeVehicleTempService.saveBatch(authorizeVehicleTempList);
            } else {
                for (int i = 0; i < size / 1000; i++) {
                    if (size / 1000 - i > 1) {
                        vehicleResult =  channelAuthorizeVehicleTempService.saveBatch(authorizeVehicleTempList.subList(1000 * i, 1000 * i + 999));
                    } else {
                        vehicleResult =  channelAuthorizeVehicleTempService.saveBatch(authorizeVehicleTempList.subList(1000 * i, size - 1));
                    }
                }
            }
        }

        //查授权区域信息
        List<ChannelAuthorizeRegion> authorizeRegionTempList = condition.getChannelAuthorizeRegionList();
        channelAuthorizeRegionService.remove(Wrappers.<ChannelAuthorizeRegion>query().lambda()
                .eq(ChannelAuthorizeRegion::getChannelId, dealer.getId()));
        if (authorizeRegionTempList.size() > 0 && authorizeRegionTempList != null) {
            for (ChannelAuthorizeRegion list : authorizeRegionTempList) {
                list.setId(null);
            }

            int size = authorizeRegionTempList.size();
            if (size <= 1000) {
               regionResult =  channelAuthorizeRegionService.saveBatch(authorizeRegionTempList);
            } else {
                for (int i = 0; i < size / 1000; i++) {
                    if (size / 1000 - i > 1) {
                        regionResult =  channelAuthorizeRegionService.saveBatch(authorizeRegionTempList.subList(1000 * i, 1000 * i + 999));
                    } else {
                        regionResult = channelAuthorizeRegionService.saveBatch(authorizeRegionTempList.subList(1000 * i, size - 1));
                    }
                }
            }

        }

        //收款账号
        List<ChannelReceivablesAccount> accountTempList = condition.getChannelAccountInfoList();
        channelAccountInfoService.remove(Wrappers.<ChannelReceivablesAccount>query().lambda()
                .eq(ChannelReceivablesAccount::getChannelId, dealer.getId()));
        if (accountTempList != null && accountTempList.size() > 0 ) {
            for (ChannelReceivablesAccount list : accountTempList) {
                list.setId(null);
                accountResult  = channelAccountInfoService.save(list);
            }
        }
        
        result = carDealerResult && coopeResult && mainBrandresult && riskResult && quotaResult && vehicleResult && regionResult && accountResult;
        return IResponse.success(result);

    }


    //保存开票账号信息
    @PostMapping("/savaInvoiceInfo")
    @ApiOperation(value = "保存开票信息")
    public IResponse savaInvoiceInfo(@RequestBody DirectCarDealerCondition condition) {

        DirectCarDealer directCarDealer = directCarDealerService.getById(condition.getId());
        directCarDealerService.getById(condition.getId());
        directCarDealer.setTaxpayerType(condition.getTaxpayerType());
        directCarDealer.setTaxpayerIdNumber(condition.getTaxpayerIdNumber());
        directCarDealer.setInvoiceTelNumber(condition.getInvoiceTelNumber());
        directCarDealer.setInvoiceAddress(condition.getInvoiceAddress());
        directCarDealer.setOpeningBank(condition.getOpeningBank());
        directCarDealer.setBankAccount(condition.getBankAccount());
        directCarDealer.setTaxRate(condition.getTaxRate());
        boolean result = directCarDealerService.updateById(directCarDealer);
        return  IResponse.success(result) ;
    }

    @RequestMapping(value = "/upQuota", method = RequestMethod.POST)
    @ApiOperation(value = "修改额度信息")
    @Transactional(rollbackFor = Exception.class)
    public IResponse upQuota(@RequestBody ChannelQuotalnfoToCaseVo vo) {

        log.info("=====================额度信息修改开始====================》");
        if(vo.getQuota() !=null && vo.getQuota().size()>0){
            for(ChannelQuotaInfo info:vo.getQuota()){
                ChannelQuotaInfo quotaInfo = channelQuotaInfoService.getOne(Wrappers.<ChannelQuotaInfo>query().lambda()
                        .eq(ChannelQuotaInfo::getChannelId, info.getChannelId())
                        .eq(ChannelQuotaInfo::getBusinessType,info.getBusinessType())
                        .eq(ChannelQuotaInfo::getQuotaType,info.getQuotaType()));
                if(quotaInfo !=null){
                    //临时额度
                    quotaInfo.setTempQuota(info.getTempQuota() == null ? BigDecimal.ZERO : info.getTempQuota());
                    //签放额度赋值
                    quotaInfo.setQuotaSigning(info.getQuotaSigning() == null ? BigDecimal.ZERO : info.getQuotaSigning());
                    //额度金额
                    quotaInfo.setQuotaAmount(info.getQuotaAmount() == null ? BigDecimal.ZERO : info.getQuotaAmount());
                    //临时额度有效期
                    quotaInfo.setValidityTermEnd(info.getValidityTermEnd());
                    //是否控制额度
                    quotaInfo.setQuotaControlSwitch(info.getQuotaControlSwitch());
                    //剩余额度= 额度+临时额度-占用额度
                    BigDecimal surplusQuota = info.getQuotaAmount().add(info.getTempQuota() ).subtract(quotaInfo.getOccupiedQuota() == null ? BigDecimal.ZERO : quotaInfo.getOccupiedQuota());
                    quotaInfo.setSurplusQuota(surplusQuota);
                    channelQuotaInfoService.updateById(quotaInfo);
                }
            }
        }
        log.info("=====================额度信息修改结束====================》");

        log.info("=====================风控信息修改开始====================》");
        if(vo.getRiskInfo() !=null){
            ChannelRiskInfo channelRiskInfo = channelRiskInfoService.getOne(Wrappers.<ChannelRiskInfo>query().lambda()
                    .eq(ChannelRiskInfo::getChannelId, vo.getRiskInfo().getChannelId())
                    .eq(ChannelRiskInfo::getBusinessType,vo.getRiskInfo().getBusinessType()));
            if(channelRiskInfo !=null){
                //应收保证金修改
                channelRiskInfo.setChannelDeposit(vo.getRiskInfo().getChannelDeposit());
                //实收保证金修改
                channelRiskInfo.setChannelDepositPaidIn(vo.getRiskInfo().getChannelDepositPaidIn());
                channelRiskInfoService.updateById(channelRiskInfo);
            }
        }
        log.info("=====================风控信息修改结束====================》");
        return IResponse.success("保存成功");
    }


    @PostMapping(value = "/upStatusCarDealerByChannelIds")
    @ApiOperation(value = "黑名单根据id停用普通车商")
    @Transactional(rollbackFor = Exception.class)
    public IResponse upStatusCarDealerByChannelIds(@RequestBody List<Long> ids) {
        if (ids.size() > 0) {
            for (int j = 0; j < ids.size(); j++) {
                CommonCarDealer channel = carDealerService.getById(ids.get(j));
                if (channel != null) {
                    channel.setStatus(BlackDic.STATUS_STOP);
                    channel.setUpdateTime(new Date(System.currentTimeMillis()));
                    channel.setUpdateBy(SecurityUtils.getUsername());
                    boolean result = carDealerService.updateById(channel);
                    //停用关联表中关联关系
                    List<ChannelCoopeCardealer> cardealerTemps = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealer>query().lambda()
                            .eq(ChannelCoopeCardealer::getCardealerId, ids.get(j))
                            .eq(ChannelCoopeCardealer::getCardealerType, BlackDic.CAR_DEALERS_ORDINARY)
                    );
                    if (cardealerTemps.size() > 0) {
                        for (ChannelCoopeCardealer temp : cardealerTemps) {
                            temp.setStatus(BlackDic.STATUS_STOP);
                            channelCoopeCardealerService.updateById(temp);
                        }
                    }
                    if (!result) {
                        return IResponse.fail("状态更新失败！");
                    }
                }
            }
        }
        return new IResponse<Boolean>().setMsg("状态更新成功");
    }

    @PostMapping(value = "/upStatusCarDealerByChannelIdsPass")
    @ApiOperation(value = "黑名单根据id启用普通车商")
    public IResponse upStatusCarDealerByChannelIdsPass(@RequestBody List<Long> ids) {
        if (ids.size() > 0) {
            for (int j = 0; j < ids.size(); j++) {
                CommonCarDealer channel = carDealerService.getById(ids.get(j));
                if (channel != null) {
                    channel.setStatus(BlackDic.STATUS_PASS);
                    channel.setUpdateTime(new Date(System.currentTimeMillis()));
                    channel.setUpdateBy(SecurityUtils.getUsername());
                    boolean result = carDealerService.updateById(channel);
                    if (!result) {
                        return IResponse.fail("状态更新失败！");
                    }
                }
            }
        }
        return new IResponse<Boolean>().setMsg("状态更新成功");
    }


    @GetMapping("/disableCarDealer/{ids}")
    @ApiOperation(value = "停用普通车商")
    @Transactional(rollbackFor = Exception.class)
    public IResponse diableCarDealer(@PathVariable String[] ids) {
        if (ids == null) {
            return IResponse.success(false);
        }
        boolean result;
        boolean update = true;
        boolean updateCoope = true;
        for (int i = 0; i < ids.length; i++) {
            CommonCarDealer commonCarDealer = carDealerService.getById(ids[i]);
            commonCarDealer.setStatus(Constants.DISABLE);
            update = carDealerService.updateById(commonCarDealer);
            //更新中间表
            List<ChannelCoopeCardealer> coopeCardealers = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealer>query().lambda()
                    .eq(ChannelCoopeCardealer::getCardealerId, ids[i])
                    .eq(ChannelCoopeCardealer::getCardealerType, Constants.COMMONCARDEALER));
            if (coopeCardealers != null && coopeCardealers.size() > 0) {
                for (ChannelCoopeCardealer coopeCardealer : coopeCardealers) {
                    coopeCardealer.setStatus(Constants.DISABLE);
                }
                updateCoope = channelCoopeCardealerService.updateBatchById(coopeCardealers);
            }
        }
        result = update && updateCoope;
        return IResponse.success(result);
    }


    @GetMapping("/disableDirectCarDealer/{ids}")
    @ApiOperation(value = "禁用直营车商")
    @Transactional(rollbackFor = Exception.class)
    public IResponse disableDirectCarDealer(@PathVariable String[] ids) {
        if (ids == null) {
            return IResponse.success(false);
        }
        boolean result;
        boolean update = true;
        boolean updateCoope = true;
        for (int i = 0; i < ids.length; i++) {
            DirectCarDealer dealer = directCarDealerService.getById(ids[i]);
            if (dealer.getChannelStatusOldCar() != null) {
                dealer.setChannelStatusOldCar(Constants.DISABLE);
            }
            if (dealer.getChannelStatus() != null) {
                dealer.setChannelStatus(Constants.DISABLE);
            }
            List<ChannelCoopeCardealer> coopeCardealerTempList = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealer>query().lambda()
                    .eq(ChannelCoopeCardealer::getCardealerId, ids[i])
                    .eq(ChannelCoopeCardealer::getCardealerType, DIRECTCARDEALER)
            );
            if (coopeCardealerTempList.size() > 0 && coopeCardealerTempList != null) {
                for (ChannelCoopeCardealer temp : coopeCardealerTempList) {
                    temp.setStatus(Constants.DISABLE);
                    updateCoope = channelCoopeCardealerService.updateById(temp);
                }
            }
            update = directCarDealerService.updateById(dealer);
        }
        result = update && updateCoope;
        return IResponse.success(result);
    }


    @GetMapping("/disableDirectCarDealerFromApply/{ids}/{channelId}/{status}")
    @ApiOperation(value = "禁用进件端直营车商")
    public IResponse disableDirectCarDealerFromApply(@PathVariable String[] ids, @PathVariable String channelId, @PathVariable String status) {
        if (ids == null || channelId == null) {
            return IResponse.success(false);
        }
        boolean updateCoope = true;
        for (int i = 0; i < ids.length; i++) {
            List<ChannelCoopeCardealer> coopeCardealerTempList = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealer>query().lambda()
                    .eq(ChannelCoopeCardealer::getCardealerId, ids[i])
                    .eq(ChannelCoopeCardealer::getCardealerType, DIRECTCARDEALER)
                    .eq(ChannelCoopeCardealer::getChannelId, channelId)
            );
            if (coopeCardealerTempList.size() > 0 && coopeCardealerTempList != null) {
                for (ChannelCoopeCardealer temp : coopeCardealerTempList) {
                    temp.setStatus(status);
                    updateCoope = channelCoopeCardealerService.updateById(temp);
                }
            }
        }
        return IResponse.success(updateCoope);
    }


    @PostMapping("/bulkEditingCustomerManager")
    @ApiOperation(value = "批量修改直营车商城市经理")
    @Transactional(rollbackFor = Exception.class)
    public IResponse bulkEditingCustomerManager(@RequestBody ChangeSalesmanCondition condition) {

        Long channelId = condition.getChannelId();
        String type = condition.getBusinessType();
        ArrayList<Long> ids = condition.getAllCarDealerIds();
        String customerManager = condition.getSalesman();

        if (ids == null || channelId == null || customerManager == null || type == null) {
            return IResponse.success(false);
        }

        boolean result = true;
        boolean result2= true;
        for (int i = 0; i < ids.size(); i++) {
            //改风控表里的城市经理
            List<ChannelRiskInfo> riskList = channelRiskInfoService.list(Wrappers.<ChannelRiskInfo>query().lambda()
                    .eq(ChannelRiskInfo::getChannelId, ids.get(i))
                    .eq(ChannelRiskInfo::getBusinessType, type));
            if (riskList != null && riskList.size() > 0) {
                for (ChannelRiskInfo risk : riskList) {
                    risk.setCustomerManager(customerManager);
                }
                result = channelRiskInfoService.updateBatchById(riskList);
                //改车商合作商中间表里的关联账户
                List<ChannelCoopeCardealer> list = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealer>query().lambda()
                        .eq(ChannelCoopeCardealer::getCardealerId, ids.get(i))
                        .eq(ChannelCoopeCardealer::getChannelId, channelId)
                        .eq(ChannelCoopeCardealer::getCardealerType, DIRECTCARDEALER)
                );
                if(list.size() > 0){
                    ChannelCoopeCardealer coopeCardealerTemp = list.get(0);
                    if (Constants.BUSINESS_TYPE_NEW_CAR.equals(type)) {
                        coopeCardealerTemp.setAssociAccount(customerManager);
                    } else {
                        coopeCardealerTemp.setAssociAccountOld(customerManager);
                    }
                    result2 = channelCoopeCardealerService.updateById(coopeCardealerTemp);
                }
            }

        }
        return result2 && result ? IResponse.success(true) : IResponse.success(false);
    }


    @GetMapping("/bulkEditingCustomerManagerFromApply/{customerManager}/{channelId}/{ids}/{type}")
    @ApiOperation(value = "批量修改进件端直营车商城市经理")
    @Transactional(rollbackFor = Exception.class)
    public IResponse bulkEditingCustomerManagerFromApply(@PathVariable String customerManager, @PathVariable String channelId, @PathVariable String[] ids, @PathVariable String type) {
        if (ids == null || channelId == null || customerManager == null || type == null) {
            return IResponse.success(false);
        }
        boolean result = true;
        boolean result2= true;
        for (int i = 0; i < ids.length; i++) {
            //改风控表里的城市经理
            List<ChannelRiskInfo> riskList = channelRiskInfoService.list(Wrappers.<ChannelRiskInfo>query().lambda()
                    .eq(ChannelRiskInfo::getChannelId, ids[i])
                    .eq(ChannelRiskInfo::getBusinessType, type));
            if (riskList != null && riskList.size() > 0) {
                for (ChannelRiskInfo risk : riskList) {
                    risk.setCustomerManager(customerManager);
                }
                result = channelRiskInfoService.updateBatchById(riskList);
            }
            //改车商合作商中间表里的关联账户
            List<ChannelCoopeCardealer> list = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealer>query().lambda()
                    .eq(ChannelCoopeCardealer::getCardealerId, ids[i])
                    .eq(ChannelCoopeCardealer::getChannelId, channelId)
                    .eq(ChannelCoopeCardealer::getCardealerType, DIRECTCARDEALER)
            );
            ChannelCoopeCardealer coopeCardealerTemp = list.get(0);
            if (Constants.BUSINESS_TYPE_NEW_CAR.equals(type)) {
                coopeCardealerTemp.setAssociAccount(customerManager);
            } else {
                coopeCardealerTemp.setAssociAccountOld(customerManager);
            }

            result2 = channelCoopeCardealerService.updateById(coopeCardealerTemp);
        }
        return result2 && result ? IResponse.success(true) : IResponse.success(false);
    }

    @GetMapping("/bulkEditingSalesman/{salesman}/{ids}")
    @ApiOperation(value = "批量修改业务员")
    @Transactional
    public IResponse bulkEditingSalesman(@PathVariable String salesman, @PathVariable String[] ids) {
        if (ids == null || salesman == null) {
            return IResponse.success(false);
        }
        boolean result = true;
        boolean result2 = true;
        for (int i = 0; i < ids.length; i++) {
            CommonCarDealer carDealer = carDealerService.getById(ids[i]);
            carDealer.setSalesMan(salesman);
            result = carDealerService.updateById(carDealer);
            List<ChannelCoopeCardealer> list = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealer>query().lambda()
                    .eq(ChannelCoopeCardealer::getCardealerId, ids[i])
                    .eq(ChannelCoopeCardealer::getCardealerType, Constants.COMMONCARDEALER)
            );
            if (list.size() > 0 && list != null) {
                for (ChannelCoopeCardealer temp : list) {
                    temp.setAssociAccount(salesman);
                }
            }
            result2 = channelCoopeCardealerService.updateBatchById(list);
        }
        return result2 && result ? IResponse.success(true) : IResponse.success(false);
    }

    @GetMapping("/bulkEditingSalesmanFromApply/{salesman}/{ids}/{channelId}")
    @ApiOperation(value = "进件端批量修改业务员")
    public IResponse bulkEditingSalesmanFromApply(@PathVariable String salesman, @PathVariable String[] ids, @PathVariable String channelId) {
        if (ids == null || salesman == null || channelId == null) {
            return IResponse.success(false);
        }
        boolean result = true;
        for (int i = 0; i < ids.length; i++) {
            List<ChannelCoopeCardealer> list = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealer>query().lambda()
                    .eq(ChannelCoopeCardealer::getCardealerId, ids[i])
                    .eq(ChannelCoopeCardealer::getChannelId, channelId)
                    .eq(ChannelCoopeCardealer::getCardealerType, Constants.COMMONCARDEALER)
            );
            if (list.size() > 0 && list != null) {
                for (ChannelCoopeCardealer temp : list) {
                    temp.setAssociAccount(salesman);
                }
            }
            result = channelCoopeCardealerService.updateBatchById(list);
        }
        return IResponse.success(result);
    }

    @GetMapping("/disableCarDealerFromCase/{ids}/{channelId}/{status}")
    @ApiOperation(value = "从进件端停用案件端普通车商")
    @Transactional(rollbackFor = Exception.class)
    public IResponse disableCarDealerFromCase(@PathVariable String[] ids, @PathVariable String channelId, @PathVariable String status) {
        if (ids == null || channelId == null) {
            return IResponse.success(false);
        }
        boolean update = true;
        for (int i = 0; i < ids.length; i++) {
            //更新中间表
            List<ChannelCoopeCardealer> coopeCardealers = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealer>query().lambda()
                    .eq(ChannelCoopeCardealer::getCardealerId, ids[i])
                    .eq(ChannelCoopeCardealer::getChannelId, channelId)
                    .eq(ChannelCoopeCardealer::getCardealerType, Constants.COMMONCARDEALER));
            if (coopeCardealers != null && coopeCardealers.size() > 0) {
                if (coopeCardealers != null && coopeCardealers.size() > 0) {
                    for (ChannelCoopeCardealer coopeCardealer : coopeCardealers) {
                        coopeCardealer.setStatus(status);
                    }
                }
                update = channelCoopeCardealerService.updateBatchById(coopeCardealers);
            }
        }
        return IResponse.success(update);
    }

    @RequestMapping(value = "/saveAccountInfo", method = RequestMethod.POST)
    @ApiOperation(value = "保存车商或渠道收款账号数据")
    public IResponse saveAccountInfo(@RequestBody List<ChannelReceivablesAccount> condition) {
        List<ChannelReceivablesAccount> channelAccountInfoList = condition;
        boolean result = true;
        channelAccountInfoService.remove(Wrappers.<ChannelReceivablesAccount>query().lambda()
                .eq(ChannelReceivablesAccount::getChannelId, channelAccountInfoList.get(0).getChannelId()));
        if (channelAccountInfoList.size() > 0) {
            for (int i = 0; i < channelAccountInfoList.size(); i++) {
                channelAccountInfoList.get(i).setId(null);
            }
            result = channelAccountInfoService.saveBatch(channelAccountInfoList);
        }
        return result ? IResponse.success(true): IResponse.success(false);
    }

    @RequestMapping(value = "/saveAccountInfoToCase", method = RequestMethod.POST)
    @Transactional
    @ApiOperation(value = "保存直营车商或渠道收款账号数据")
    public IResponse saveAccountInfoToCase(@RequestBody AccountToCaseCondition accountToCaseCondition) {
        List<ChannelReceivablesAccount> channelAccountInfoList = accountToCaseCondition.getAccountTempList();
        ChannelBaseInfo channelBaseInfoTemp = accountToCaseCondition.getChannelBaseInfoTemp();
        boolean result = true;

        List<ChannelBaseInfo> baseInfos = channelBaseInfoService.list(Wrappers.<ChannelBaseInfo>query().lambda().eq(ChannelBaseInfo::getChannelId, channelBaseInfoTemp.getId()));
        ChannelBaseInfo channelBaseInfo = baseInfos.get(0);

        channelBaseInfo.setTaxpayerType(channelBaseInfoTemp.getTaxpayerType());
        channelBaseInfo.setTaxpayerIdNumber(channelBaseInfoTemp.getTaxpayerIdNumber());
        channelBaseInfo.setInvoiceTelNumber(channelBaseInfoTemp.getInvoiceTelNumber());
        channelBaseInfo.setInvoiceAddress(channelBaseInfoTemp.getInvoiceAddress());
        channelBaseInfo.setOpeningBank(channelBaseInfoTemp.getOpeningBank());
        channelBaseInfo.setBankAccount(channelBaseInfoTemp.getBankAccount());
        channelBaseInfo.setTaxRate(channelBaseInfoTemp.getTaxRate());
        channelBaseInfoService.updateById(channelBaseInfo);

        channelAccountInfoService.remove(Wrappers.<ChannelReceivablesAccount>query().lambda()
                .eq(ChannelReceivablesAccount::getChannelId, channelAccountInfoList.get(0).getChannelId()));
        if (channelAccountInfoList.size() > 0) {
            for (int i = 0; i < channelAccountInfoList.size(); i++) {
                channelAccountInfoList.get(i).setId(null);
            }
            result = channelAccountInfoService.saveBatch(channelAccountInfoList);
        }
        return result ? IResponse.success(true): IResponse.success(false);
    }


    @RequestMapping(value = "/getAuthorizeRegion", method = RequestMethod.POST)
    @ApiOperation(value = "查车商授权区域")
    public IResponse getAuthorizeRegion(@RequestBody DirectCarDealerCondition condition) {
        //车商id,业务类型,是否是父级,父级id
        Long id = condition.getId();
        String businessType = condition.getBusinessType();
        String parentId = condition.getParentId();
        String isParent = condition.getIsParent();
        List<ChannelAuthorizeRegion> channelAuthorizeRegion = new ArrayList<>();

        if(id == null || businessType==null || isParent==null){
            return IResponse.fail("传入参数有误");
        }

        if(Constants.IS_PARENT.equals(isParent)){
            //查省份
            channelAuthorizeRegion = channelAuthorizeRegionService.list(Wrappers.<ChannelAuthorizeRegion>query().lambda()
                    .eq(ChannelAuthorizeRegion::getChannelId,id)
                    .eq(ChannelAuthorizeRegion::getIsParent,Constants.IS_PARENT)
                    .eq(ChannelAuthorizeRegion::getBusinessType,businessType)
                    .ne(ChannelAuthorizeRegion::getParentId,Constants.PARENT_ID_ZERO)
            );
            return IResponse.success(channelAuthorizeRegion);
        }

        if(parentId == null || parentId ==""){
            return IResponse.fail("传入参数有误");
        }else{
            //查城市
            channelAuthorizeRegion = channelAuthorizeRegionService.list(Wrappers.<ChannelAuthorizeRegion>query().lambda()
                    .eq(ChannelAuthorizeRegion::getChannelId, id)
                    .ne(ChannelAuthorizeRegion::getIsParent, Constants.IS_PARENT)
                    .eq(ChannelAuthorizeRegion::getBusinessType, businessType)
                    .eq(ChannelAuthorizeRegion::getParentId, parentId)
            );
        }
        return IResponse.success(channelAuthorizeRegion);
    }

    // 批量修改区域经理人
    @Transactional
    @PostMapping("/batchManager")
    @ApiOperation(value = "批量修改区域经理")
    public IResponse<Boolean> batchManager(@RequestBody BatchManagerDTO dto) {
        String[] ids=dto.getIds().split(",");
        Set<Long> channelIds =new HashSet<>();
        if(ids.length>0){
            for (int j = 0; j < Arrays.asList(ids).size(); j++) {
                Long id = Long.valueOf(Arrays.asList(ids).get(j));
                channelIds.add(id);
            }
        }
        List<ChannelRiskInfo> aa =channelRiskInfoService.list(Wrappers.<ChannelRiskInfo>query()
                .lambda().eq(ChannelRiskInfo::getBusinessType, dto.getBorder()).in(ChannelRiskInfo::getChannelId,channelIds));
        if(aa.size()>0){
            aa.forEach(en -> {
                en.setCustomerManager(dto.getAreaManager());
            });
            channelRiskInfoService.updateBatchById(aa);
        }
        return new IResponse<Boolean>().setMsg("修改成功！");
    }


    @RequestMapping(value = "/getCarDealerByChannelId", method = RequestMethod.POST)
    @ApiOperation(value = "根据合作商id 查询旗下的车商")
    public IResponse getCarDealerByChannelId(@RequestBody ChannelBaseInfo channeld) {
            Set<ChannelDealer> dealer =new HashSet<>();
            ChannelBaseInfo baseInfo =channelBaseInfoService.getById(channeld.getChannelId());
             ChannelDealer d =new ChannelDealer();
             d.setDealerName(baseInfo.getChannelFullName());
             d.setId(baseInfo.getId());
             dealer.add(d);
            if(!ChannelBelongEnum.DIRECT.equals(baseInfo.getChannelBelong())){
                // 说明是普通车商
                List<ChannelCoopeCardealer> temps = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealer>query().lambda()
                        .eq(ChannelCoopeCardealer::getChannelId, channeld.getChannelId())
                        .eq(ChannelCoopeCardealer::getCardealerType, Constants.COMMONCARDEALER));
                // 再去普通车商表去查询信息
                List<Long> ids =new ArrayList<>();
                if(temps.size()>0){
                    for (ChannelCoopeCardealer t:temps){
                        ids.add(t.getCardealerId());
                    }
                    List<CommonCarDealer> list =carDealerService.list(Wrappers.<CommonCarDealer>query().lambda()
                            .in(CommonCarDealer::getId, ids));
                    if(list.size()>0){
                        for (CommonCarDealer c :list){
                            ChannelDealer dd =new ChannelDealer();
                            dd.setDealerName(c.getCardealerName());
                            dd.setId(c.getId());
                            dealer.add(dd);
                        }
                    }
                }
            }else {
                List<ChannelCoopeCardealer> temps = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealer>query().lambda()
                        .eq(ChannelCoopeCardealer::getChannelId, channeld.getChannelId())
                        .eq(ChannelCoopeCardealer::getCardealerType, DIRECTCARDEALER));
                List<Long> ids =new ArrayList<>();
                if(temps.size()>0){
                    for (ChannelCoopeCardealer t:temps){
                        ids.add(t.getCardealerId());
                    }
                    List<ChannelBaseInfo> list =channelBaseInfoService.list(Wrappers.<ChannelBaseInfo>query().lambda()
                            .in(ChannelBaseInfo::getId, ids));
                    if(list.size()>0){
                        for (ChannelBaseInfo c :list){
                            ChannelDealer dd =new ChannelDealer();
                            dd.setDealerName(c.getChannelFullName());
                            dd.setId(c.getId());
                            dealer.add(dd);
                        }
                    }
                }

            }

        return IResponse.success(dealer);
    }

    @RequestMapping(value = "/getAllCarDealers", method = RequestMethod.POST)
    @ApiOperation(value = "查询所有的车商")
    public IResponse getAllCarDealers(@RequestBody CarDealerCondition condition) {
        return IResponse.success(carDealerService.getAllCarDealers(condition));
    }

    @GetMapping("/getCarDealListForZY")
    @ApiOperation(value = "根据合作商账户返回此账户下的车商列表信息")
    public IResponse getCarDealersByUserIds(CarDealerCondition condition) {
        List<String> userIds = condition.getUserIds();

        String cardealerType = condition.getCardealerType();
        String channelId = condition.getChannelId();
        String businessType = condition.getBusinessType();
        if (CollectionUtil.isEmpty(userIds) || StringUtils.isEmpty(cardealerType) || StringUtils.isEmpty(channelId)) {
            return IResponse.fail("查询参数为空");
        }
        if (DIRECTCARDEALER.equals(cardealerType) && businessType == null) {
            return IResponse.fail("直营合作商必传业务类型");
        }
        String aSwitch = null;
        List<ChannelBaseInfo> channelList = channelBaseInfoService.list(Wrappers.<ChannelBaseInfo>query().lambda()
                .eq(ChannelBaseInfo::getChannelId, channelId));
        if (channelList != null && channelList.size() > 0) {
            aSwitch = channelList.get(0).getPersonRelCardealerSwitch();
        } else {
            return IResponse.fail("渠道基本信息表中无此合作商信息");
        }
        return carDealerService.getCarDealersByUserIds(userIds, cardealerType, aSwitch, channelId, businessType);
    }

}
